<?php
class login {
	private $mysql;
	public $tokenid;
	public $userid = -1;
	public $userlevel;
	public $islogined = false;
	public $agentid = -1;
	public $companyid = -1;
#	public $brandid = -1;

	public function __construct ($mysql) {
//	    ini_set('Session.Timeout', '1');
		$this->mysql = $mysql;
		if (array_key_exists ('tokenid', $_REQUEST) && $_REQUEST['tokenid'] != '' && $this->checkLogined ($_REQUEST['tokenid'])) {
			$this->tokenid = $_REQUEST['tokenid'];
			session_id ($this->tokenid);
			session_start ();
		} else {
			session_start ();
			$this->tokenid = session_id ();
		}
	}

	public function setLogined ($userid) {
		if ($this->checkLogined ($this->tokenid)) {
			$result = $this->mysql->query (sprintf ('UPDATE `Session` SET `User_id`=\'%d\', `Session_lastactivetime`=NOW() WHERE `Session_tokenid`=\'%s\';', $this->mysql->real_escape_string ($userid), $this->mysql->real_escape_string ($this->tokenid)));
		} else {
			$result = $this->mysql->query (sprintf ('INSERT INTO `Session` (`User_id`, `Session_tokenid`, `Session_lastactivetime`) VALUES (\'%d\', \'%s\', NOW());', $this->mysql->real_escape_string ($userid), $this->mysql->real_escape_string ($this->tokenid)));
		}
		$result->free_result ();
	}

	public function checkLogined ($tokenid) {
		$result = $this->mysql->query (sprintf ('SELECT `User_id`, `User_name`, `UserLevel_id` FROM `Logineduser` WHERE `Session_tokenid`=\'%s\';', $this->mysql->real_escape_string ($tokenid)));
		$len = $result->num_rows ();
		if ($len != 0) {
			$user = $result->fetch_array ();
			$this->userid = $user['User_id'];
			$this->userlevel = $user['UserLevel_id'];
			if ($this->userlevel == 2 && !$this->agentID ($this->userid)) {
				$this->userlevel = 0;
			}
		}
		$result->free_result ();
		if ($len == 0) {
			return false;
		} else {
			return true;
		}
	}

/*	private function agentID ($uid) {
		$result = $this->mysql->query (sprintf ('SELECT `Agent_id`,`Company_id` FROM `AgentDetail` WHERE `User_ID`=\'%d\';', $this->mysql->real_escape_string ($uid)));
		$len = $result->num_rows ();
		if ($len != 0) {
			$agent = $result->fetch_array ();
			$this->agentid = $agent['Agent_id'];
			$this->companyid = $agent['Company_id'];
		}
		$result->free_result ();
		if ($len == 0) {
			return false;
		} else {
			return true;
		}	
	}*/
	
	public function logout () {
		$_SESSION = array ();
		if (ini_get ('session.use_cookies')) {
			$params = session_get_cookie_params ();
			setcookie (session_name (), '', time () - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
		}
		session_destroy ();
	}
}
?>